<template>
    <div>
        <el-form :model="params">
            <el-row :gutter="12">
                <el-col :span="6">
                    <el-form-item label="仓库编码">
                        <el-input v-model="params.warehouseCode" placeholder="请输入编码"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="仓库名称">
                        <el-input v-model="params.warehouseName" placeholder="请输入名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
                <el-button type="primary" plain @click="paramsReset" :icon="Refresh">重置</el-button>
            </el-row>

            <el-button style="background-color:#ADD8E6" @click="insert" :icon="Plus">新增</el-button>
            <el-button style=" background-color: #90EE90" :icon="Edit" :disabled="isSingleRowSelected"
                @click="updateid">修改</el-button>
            <el-button style="background-color: #FFCCCB" @click="Delete1" plain :disabled="deleteDisabled"
                :icon="Delete">删除</el-button>

            <div style="display: flex; flex-direction: column; gap: 10px;">
                <el-table style="width: 100%" :data="salesorder" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" :selectable="selectable" width="50"></el-table-column>
                    <el-table-column prop="warehouseCode" label="仓库编码" width="150"></el-table-column>
                    <el-table-column prop="warehouseName" label="仓库名称" width="150"></el-table-column>
                    <el-table-column prop="warehousePosition" label="位置" width="150"></el-table-column>
                    <el-table-column prop="area" label="面积" width="150"></el-table-column>
                    <el-table-column prop="personInCharge" label="负责人" width="150"></el-table-column>
                    <el-table-column prop="remark" label="备注" width="150"></el-table-column>
                    <el-table-column label="操作" width="300px">
                        <template #default="scope">
                            <el-button type="primary" link @click="kq(scope.row)">库区</el-button>
                            <el-button type="primary" link @click="update(scope.row)" :icon="Edit">修改</el-button>
                            <el-button type="primary" link @click="Delete2(scope.row)" :icon="Delete">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <el-row>
                <el-col :span="24">
                    <div class="demo-pagination-block">
                        <el-pagination :current-page="params.currentPage" :page-size="params.pageSize" background
                            :default-page-size="params.pageSize" :page-sizes="pageSizes"
                            layout="total,sizes,prev,pager,next,jumper" :total="pageResult.total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange">
                        </el-pagination>
                    </div>
                </el-col>
            </el-row>
        </el-form>




        <!-- 弹窗 -->
        <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="50%" @close="handleClose">
            <el-form ref="form" :model="formdata" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="仓库编码">
                            <el-input v-model="formdata.warehouseCode" placeholder="请输入仓库编码"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="仓库名称">
                            <el-input v-model="formdata.warehouseName" placeholder="请输入仓库名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="位置">
                            <el-input v-model="formdata.warehousePosition" placeholder="请输入位置" type="textarea"
                                autosize></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="面积">
                            <el-input-number v-model="formdata.area" @change="handleChange" :min="0" :max="2000"
                                label="面积"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="负责人">
                            <el-input v-model="formdata.personInCharge" placeholder="请输入负责人"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="formdata.remark" placeholder="请输入备注" type="textarea" autosize></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onSubmit">确定</el-button>
                    <el-button @click="close">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { findWarehouses, insertWarehouses, updateWarehouses, deleteWarehouses } from '@/apis/xms/index';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Delete, Plus, Edit } from '@element-plus/icons-vue';

import { useLayoutStore } from '@/stores/settings'
import router from '@/router/index'
const pageResult = ref({ total: 0 }); // 初始值包含 total 属性
const isSingleRowSelected = ref(true) // 修改按钮禁用状态,默认禁用
let roleVal = ref([]); //选中行
let salesorder = ref([]); // 表格数据
const title = ref(""); // 弹窗标题
const visible = ref(false); // 弹窗状态
const formdata = ref({
    warehouseCode: '',
    warehouseName: '',
    warehousePosition: '',
    area: 1000, // 设置初始值为 1000
    personInCharge: '',
    remark: ''
});


const settingStore = useLayoutStore()

let ids = ref([]) // 选中行的id数组
const deleteDisabled = ref(true) // 删除按钮禁用状态,默认禁用
// 分页大小
const pageSizes = [2, 5, 8, 10];

const params = ref({
    currentPage: 1,
    pageSize: 5,
    warehouseCode: '',
    warehouseName: '',
    warehousePosition: '',
    area: null,
    personInCharge: '',
    remark: '',
    status: ''
});


// 搜索条件
const handleSearch = async () => {
    pageResult.value = await findWarehouses(params.value)
    salesorder.value = pageResult.value.records
}
//处理分页大小
const handleSizeChange = async (size) => {
    params.value.pageSize = size
    pageResult.value = await findWarehouses(params.value)
    salesorder.value = pageResult.value.records
}

//处理当前分页数据
const handleCurrentChange = async (currentPage) => {
    params.value.currentPage = currentPage
    pageResult.value = await findWarehouses(params.value)
    salesorder.value = pageResult.value.records
}

//查询数据
onMounted(async () => {
    pageResult.value = await findWarehouses(params.value)
    console.log(pageResult.value)
    salesorder.value = pageResult.value.records
})


/**
 * 新增弹窗
 */
const insert = () => {
    visible.value = true;
    title.value = "新增仓库";
}
/**
 * 修改弹窗
 */
const update = (row) => {
    console.log(row)
    visible.value = true;
    title.value = "修改仓库";
    formdata.value = { ...row }; // 直接使用 row 的数据  

}

const updateid = () => {
    visible.value = true;
    title.value = "修改仓库";
}



const kq = (row) => {
    console.log(router)
    if (settingStore.tabs.length <= 0 || !settingStore.tabs.some(item => item.name == '/produce/warehousing/warehouseArea')) {
        settingStore.tabs.push({
            name: '/produce/warehousing/warehouseArea',
            label: '库区设置',
        })
    }
    settingStore.menuActive.name = '/produce/warehousing/warehouseArea'
    router.push({
        path: '/produce/warehousing/warehouseArea',
        name: 'warehouseArea',
        params: { id: row.warehouseId }
    })
}



const onSubmit = async () => {
    if (title.value == "新增仓库") {
        await insertWarehouses(formdata.value)
    } else {
        await updateWarehouses(formdata.value)
    }
    visible.value = false
    ElMessage.success(`${title.value}成功`)
    handleSearch();

}

const handleSelectionChange = (val) => {
    deleteDisabled.value = !val.length
    ids.value = val.map(item => item.warehouseId) // 使用map方法过滤出选中行的logId数组

    roleVal.value = val.map(item => item); // 存储选中行的完整数据
    isSingleRowSelected.value = !(val.length === 1); // 如果只有一个选中行，则启用修改按钮
    if (!isSingleRowSelected.value) {
        formdata.value = { ...val[0] };//把选中的这条数据添加给修改数据（）
    }
}



//批量删除
const Delete1 = async (index, row) => {
    ElMessageBox.confirm(`是否确认删除访问编号为${ids.value.join(',')}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 调用删除API  
        await deleteWarehouses(ids.value);  // 将单个ID传递给 deletesspplier 方法
        console.log(`删除的ID:`, ids.value);
        pageResult.value = await findWarehouses(params.value);
        salesorder.value = pageResult.value.records;
        ids.value = [] // 重置选中行的id数组
        ElMessage({ type: 'success', message: '删除成功' });
        handleSearch();  // 重新查询数据  
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};


//行内删除
const Delete2 = async (row) => {
    ElMessageBox.confirm(`是否确认删除访问编号为${row.warehouseId}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 调用删除API  
        await deleteWarehouses([row.warehouseId]);  // 将单个ID传递给 deletesspplier 方法

        console.log(`删除的ID:`, row.warehouseId);

        // 从表格数据中移除当前行
        salesorder.value = salesorder.value.filter(item => item.warehouseId !== row.warehouseId);

        ElMessage({ type: 'success', message: '删除成功' });
        handleSearch();  // 重新查询数据  
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};



/**
 * 自定义删除选中行的处理方法
 * @param row 行数据
 */
const selectable = (row) => {
    // 表示所有行数据都可以被选中，可以自定义选择逻辑
    return true
}

/**
 * 关闭弹窗,处理数据
 */
const handleClose = () => {
    resetData()
}
/**
 * 重置数据
 */
function resetData() {
    formdata.value = {}
    title.value = ''
}



let close = () => {
    visible.value = false;
    loadData();
};

/**
 * 加载数据
 */
const loadData = async () => {
    await handleSearch();
};

/**
 * 重置搜索参数
 */
const paramsReset = () => {
    params.value = {
        warehouseCode: '',
        warehouseName: '',
    }
    handleSearch();
}
</script>

<style scoped>
.demo-pagination-block {
    display: flex;
    /* 使其成为 flexbox 容器 */
    justify-content: flex-end;
    /* 将内容对齐到右侧 */
    margin-top: 20px;
}
</style>
